<template>
  <div class="subscribe" :class="pool.isSubscribed ? 'active' : ''" v-if="isHome">
    <span v-if="!pool.isSubscribed" @click.stop="onUnSubClick(pool, jumpTrackingPool)">+订阅</span>
    <span v-else @click.stop="onSubscribedClick(pool)">已订阅</span>
  </div>
</template>

<script>
import { reqBuyStrategy } from '@/apis/pool.api';
import { BASE_URL } from '@/config/pool';
import { Dialog } from '@atom/atom-ui';
import tools from '@/lib/tools';
export default {
  name: 'SubscribeComponent',
  props: {
    pool: {
      type: Object,
      default: () => ({}),
    },
    isHome: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      isLock: false,
    };
  },
  methods: {
    // 未订阅点击
    async onUnSubClick(pool, callback) {
      this.$emit('closeSubTips');
      if (this.isLock) {
        return;
      }
      this.isLock = true;
      try {
        const res = await reqBuyStrategy({ gpc_id: pool.id, gpc_type: 1 });
        if (res.status_code) {
          // 上报
          return;
        }
        // 未定制跟踪池
        if (!res.data.exist) {
          Dialog.confirm({
            title: '定制跟踪池',
            message: '订阅股池需要先定制该股池的跟踪池，是否去定制？',
            confirmButtonText: '去定制',
          })
            .then(() => {
              callback();
            })
            .catch(() => {
              // on cancel
            });
        } else {
          this.$emit('setSubGpcId');
        }
      } catch (err) {
        // shibai
      } finally {
        this.isLock = false;
      }
    },
    // 已订阅点击
    onSubscribedClick() {
      this.$emit('setSubGpcId');
    },
    // 跳转详情页跟踪池
    jumpTrackingPool() {
      location.href = `${BASE_URL}details?gpc_id=${this.pool.id}&name=${
        this.pool.name
      }&product=${window.getParam('product')}&tab=2`;
    },
    // 在详情页切换到跟踪池
    toggleTrackingPool() {
      const trackingNum = 2;
      this.$emit('setActiveTab', trackingNum);
    },
  },
  watch: {
    pool: {
      handler(nval) {
        if (this.isHome) {
          return;
        }
        const textContent = nval.isSubscribed ? '已订阅' : '+订阅';
        tools.setTitlebar(textContent, () => {
          this.onUnSubClick(
            nval,
            nval.isSubscribed ? this.onSubscribedClick : this.toggleTrackingPool
          );
        });
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
.subscribe {
  width: 60px;
  height: 24px;
  border-radius: 2px;
  font-size: 14px;
  letter-spacing: 0;
  text-align: center;
  line-height: 24px;
  color: #ff2436;
  background: rgba(255, 36, 54, 0.1);
  &.active {
    color: var(--text-2);
    background: #f5f5f5;
  }
}
[theme-mode='black'] .subscribe.active {
  background: #292929;
}
</style>
